package com.server.common.redis;


import com.server.common.code.utils.GsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisService{

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 设置值
     * @author LXC
     * @date 2022/4/26 23:42
     */
    public void setValue(final String key, final Object value){
        String valueString = "";
        if(value instanceof String){
            valueString = (String) value;
        }else{
            valueString = GsonUtils.getGson().toJson(value);
        }
        redisTemplate.opsForValue().set(key,valueString);
    }

    /**
     * 设置值
     * @author LXC
     * @date 2022/4/26 23:42
     */
    public void setValue(final String key, final Object value, final Long time, final TimeUnit timeUint){
        setValue(key,value);
        redisTemplate.expire(key,time,timeUint);
    }

    /**
     * 获取
     * @author LXC
     * @date 2022/4/26 23:47
     */
    public <T> T getValue(final String key,Class<T> t){
        try {
            String value = (String) redisTemplate.opsForValue().get(key);
            return (T) GsonUtils.getGson().fromJson(value,t);
        }catch (Exception e){
            log.error("redis value 不合法--key:"+key);
        }
        return null;
    }

    public String getValue(final String key){
        try {
            Object value = redisTemplate.opsForValue().get(key);
            if(ObjectUtils.isEmpty(value)){
                return "";
            }
            return String.valueOf(value);
        }catch (Exception e){
            log.error("redis value 不合法--key:"+key);
        }
        return "";
    }

}
